// ... 选择器相关所有代码都放到这个函数里 ...
function activateSelectorMode() {
    // 选择器浮层的 HTML
    const selectorHtml = `
      <div id="lcs-selector-tooltip" style="display:none;position:fixed;right:20px;bottom:20px;z-index:99999;cursor:move;">
        <div class="lcs-selector-menu" id="lcs-selector-menu">
          <!-- 选择器内容会在这里动态插入 -->
        </div>
      </div>
    `;

    // 插入浮层到页面
    if (!document.getElementById('lcs-selector-tooltip')) {
        document.body.insertAdjacentHTML('beforeend', selectorHtml);
    }
    const tooltip = document.getElementById('lcs-selector-tooltip');
    const menu = document.getElementById('lcs-selector-menu');

    // 拖动相关变量
    let isDragging = false;
    let offsetX = 0;
    let offsetY = 0;

    tooltip.addEventListener('mousedown', function(e) {
        isDragging = true;
        const rect = tooltip.getBoundingClientRect();
        offsetX = e.clientX - rect.left;
        offsetY = e.clientY - rect.top;
        tooltip.style.display = 'block';
        tooltip.style.left = rect.left + 'px';
        tooltip.style.top = rect.top + 'px';
        tooltip.style.right = '';
        tooltip.style.bottom = '';
        e.preventDefault();
    });

    window.addEventListener('mousemove', function(e) {
        if (isDragging) {
            tooltip.style.left = (e.clientX - offsetX) + 'px';
            tooltip.style.top = (e.clientY - offsetY) + 'px';
        }
    });

    window.addEventListener('mouseup', function() {
        isDragging = false;
    });

    function getSelectors(el) {
        if (!el) return [];
        const selectors = [];
        // id 选择器
        if (el.id) selectors.push(`#${el.id}`);
        // class 选择器
        if (el.classList && el.classList.length > 0) {
            selectors.push('.' + Array.from(el.classList).join('.'));
        }
        // 标签名
        selectors.push(el.tagName.toLowerCase());
        // attributes 选择器
        if (el.attributes) {
            let attrs = [];
            for (let attr of el.attributes) {
                if (attr.name !== 'class' && attr.name !== 'id' && attr.value) {
                    attrs.push(`[${attr.name}="${attr.value}"]`);
                }
            }
            if (attrs.length > 0) selectors.push(el.tagName.toLowerCase() + attrs.join(''));
        }
        // 唯一 CSS 路径
        selectors.push(getUniqueSelector(el));
        return selectors;
    }

    // 生成唯一 CSS 路径
    function getUniqueSelector(el) {
        if (!(el instanceof Element)) return '';
        let path = [];
        while (el && el.nodeType === Node.ELEMENT_NODE && el !== document.body) {
            let selector = el.nodeName.toLowerCase();
            if (el.id) {
                selector += `#${el.id}`;
                path.unshift(selector);
                break;
            } else {
                // nth-child
                let sib = el,
                    nth = 1;
                while ((sib = sib.previousElementSibling)) {
                    if (sib.nodeName.toLowerCase() === selector) nth++;
                }
                selector += `:nth-child(${nth})`;
            }
            path.unshift(selector);
            el = el.parentNode;
        }
        return path.length ? path.join(' > ') : '';
    }

    function showTooltip() {
        tooltip.style.display = 'block';
        if (!tooltip.style.left && !tooltip.style.top) {
            tooltip.style.right = '20px';
            tooltip.style.bottom = '20px';
        }
    }

    function hideTooltip() {
        tooltip.style.display = 'none';
    }

    document.addEventListener('mouseover', mouseoverHandler);
    document.addEventListener('mouseout', mouseoutHandler);

    function mouseoverHandler(e) {
        if (tooltip.contains(e.target)) return; // 避免浮层自身触发
        const el = e.target;
        const selectors = getSelectors(el);
        menu.innerHTML = selectors.map(sel => `<div class=\"lcs-selector-item\">${sel}</div>`).join('');
        showTooltip();
    }

    function mouseoutHandler(e) {
        hideTooltip();
    }
}

window.lcsSelectorActivate = activateSelectorMode;

document.getElementById('activate-btn').addEventListener('click', function() {
    chrome.tabs.query({ active: true, currentWindow: true }, function(tabs) {
        chrome.scripting.executeScript({
            target: { tabId: tabs[0].id },
            func: () => window.lcsSelectorActivate && window.lcsSelectorActivate()
        });
    });
});